<!--
 * @Author: ailin
 * @Date: 2022-12-08 17:22:25
 * @LastEditors: ailin
 * @LastEditTime: 2023-09-05 19:17:00
 * @Description: file content
 * @FilePath: /pay_platform/src/views/ule/setPay/setPayWordNew.vue
-->
<template>
  <div class="container">
    <van-tabs :active="data.activeName" @change="data.changeTabs">
      <van-tab title="" name="tab0">
        <div class="sms_con">
          <p class="title">输入短信验证码</p>
          <p class="tips tops_17">已发送短信验证码到您的手机号</p>
          <p class="tips">{{ plusXing(data.phoneNumber, 4, 3, 4) || "" }}</p>
          <van-config-provider :theme-vars="tabOne.themeVars">
            <!-- 密码输入框 -->
            <van-password-input
              :mask="false"
              class="tops_50"
              :value="tabOne.password"
              length="6"
              :focused="tabOne.showKeyboard"
              @focus="tabOne.showKeyboard = true"
            />
            <p v-if="sendSms.smsStatus == 0" class="tips tops_35">重发验证码</p>
            <p v-else class="tips tops_35 tipsActive">重发验证码({{ sendSms.smsSecond }}s)</p>
            <!-- 数字键盘 -->
            <van-number-keyboard
              v-model="tabOne.password"
              maxlength="6"
              :show="tabOne.showKeyboard"
              @blur="tabOne.showKeyboard = false"
            />
          </van-config-provider>
        </div>
      </van-tab>
      <van-tab title="" name="tab1">
        <div class="password_con">
          <p class="title tops_82">请输入您的旧支付密码</p>
          <van-field
            v-model="tabTwo.password"
            class="tops_41"
            input-align="center"
            type="password"
            placeholder="请输入您的旧支付密码"
          />
          <div v-if="data.phoneNumber" class="forget_pwd"><span @click="tabTwo.forget">忘记旧密码？</span></div>
          <div class="submit_btn" :class="{ disabled: !tabTwo.password }" @click="tabTwo.toNext()">确认</div>
        </div>
      </van-tab>
      <van-tab title="" name="tab2">
        <div class="sms_con">
          <p class="tips tops_82">为保障您的资金安全，</p>
          <p class="tips">请设置一个新的6位数支付密码</p>
          <van-config-provider :theme-vars="tabThree.themeVars">
            <!-- 密码输入框 -->
            <van-password-input
              class="tops_41"
              length="6"
              :value="tabThree.password"
              :focused="tabThree.showKeyboard"
              @focus="tabThree.showKeyboard = true"
            />
            <!-- 数字键盘 -->
            <van-number-keyboard
              v-model="tabThree.password"
              maxlength="6"
              :show="tabThree.showKeyboard"
              @blur="tabThree.showKeyboard = false"
            />
          </van-config-provider>
        </div>
      </van-tab>
      <van-tab title="" name="tab3">
        <div class="sms_con">
          <p class="tips tops_82">请再次输入密码</p>
          <van-config-provider :theme-vars="tabFour.themeVars">
            <!-- 密码输入框 -->
            <van-password-input
              class="tops_41"
              :value="tabFour.password"
              length="6"
              :focused="tabFour.showKeyboard"
              @focus="tabFour.showKeyboard = true"
            />
            <!-- 数字键盘 -->
            <van-number-keyboard
              v-model="tabFour.password"
              maxlength="6"
              :show="tabFour.showKeyboard"
              @blur="tabFour.showKeyboard = false"
            />
          </van-config-provider>
        </div>
      </van-tab>
    </van-tabs>
  </div>
</template>
<script setup>
import { onMounted, reactive, watch } from "vue"
import { useRoute, useRouter } from "vue-router"
import { plusXing, changeSearch, loadScript, browser, setAppTitle, delLocalStorage } from "@/assets/js/common.js"
import {
  // getSmsCode,
  // setPayWord,
  updatePayWord,
  getMobileNum,
  // sendCodeReset,
  // resetPayPwd,
  verifyAccountSecurity
} from "@/assets/js/api/api.js"
import { showSuccessToast, showToast } from "vant"
import { encrypted } from "@/assets/js/DES.js"
const route = useRoute()
const router = useRouter()

//第一个tab使用的相关数据及方法
const tabOne = reactive({
  themeVars: {
    passwordInputMargin: "0 22.5px",
    passwordInputRadius: "0",
    borderColor: "#c2c2c2",
    passwordInputHeight: "55px",
    passwordInputCursorWidth: "3px",
    passwordInputCursorHeight: "22px"
  },
  showKeyboard: true,
  password: ""
})
//第二个tab相关数据及方法
const tabTwo = reactive({
  password: "",
  toNext: () => {
    if (!tabTwo.password) {
      return false
    }
    //密码验证
    verifyAccountSecurity(
      {
        payPwd: encrypted(tabTwo.password), // 支付密码
        channel: "h5" // 渠道
      },
      "",
      "jsonCallback"
    ).then((res) => {
      console.log("====密码验证", res)
      if (res.code == "0000") {
        //验证通过进入到新密码设置
        data.activeName = "tab2" //切换到新密码输入
        setAppTitle("设置新支付密码")
      } else {
        showToast(res.msg)
      }
    })
  },
  forget: () => {
    router.push(`/setPayNumber?status=r&mobile=${data.phoneNumber}&isOpenNewPay=1`)
    //神策埋点-忘记密码-点击
    window.uleStatUtil &&
      window.uleStatUtil.sendSensorTrack("btnClick", {
        ule_title: window.document.title,
        button_name: "旧密码-忘记密码",
        platform_type: data.getPageType(),
        key_business_name: ""
      })
  }
})
//第三个tab相关数据及方法
const tabThree = reactive({
  themeVars: {
    passwordInputMargin: "0 22.5px",
    passwordInputRadius: "0",
    borderColor: "#c2c2c2",
    passwordInputHeight: "55px",
    passwordInputCursorWidth: "3px",
    passwordInputCursorHeight: "22px"
  },
  showKeyboard: true,
  password: ""
})
//第四个tab相关数据及方法
const tabFour = reactive({
  themeVars: {
    passwordInputMargin: "0 22.5px",
    passwordInputRadius: "0",
    borderColor: "#c2c2c2",
    passwordInputHeight: "55px",
    passwordInputCursorWidth: "3px",
    passwordInputCursorHeight: "22px"
  },
  showKeyboard: true,
  password: "",
  newPassword: "",
  //开通生物支付
  openPay: () => {
    loadScript("//i2.ulecdn.com/ulewap/j/cashierDesk/dsbridge.js", (res) => {
      try {
        dsBridge.call("openBiometricPay", function (ret) {
          //0 取消;1指纹失败次数过多;2成功
          console.log("openBiometricPay", ret)
          if (ret == 2) {
            showSuccessToast("开通成功")
            delLocalStorage("dontOpenPay") //清理缓存状态
            setTimeout(() => {
              dsBridge.call("generalAction", { type: "0", ios_action: "ulePopView", android_action: "ulePopView" })
            }, 2000)
          } else if (ret == 1) {
            if (route.query.isSetting == 1) {
              showToast("多次验证错误，请稍后再试")
              setTimeout(() => {
                dsBridge.call("generalAction", { type: "0", ios_action: "ulePopView", android_action: "ulePopView" })
              }, 2000)
              return false
            }
            //开通失败通知收银台页面
            dsBridge.call("generalAction", {
              type: "6",
              ios_action: JSON.stringify({
                functionName: "NotifyTestPay",
                functionParams: "noOpen"
              }),
              android_action: JSON.stringify({
                functionName: "NotifyTestPay",
                functionParams: "noOpen"
              }),
              needlogin: "false",
              logTitle: ""
            })
          } else {
            //如果是app的设置页面进入的，验证完密码直接关闭当前webview页面,只有app进入此页面传参数setting=1
            if (route.query.isSetting == 1) {
              dsBridge.call("generalAction", { type: "0", ios_action: "ulePopView", android_action: "ulePopView" })
              return false
            }
            //开通失败通知收银台页面
            dsBridge.call("generalAction", {
              type: "6",
              ios_action: JSON.stringify({
                functionName: "NotifyTestPay",
                functionParams: "noOpen"
              }),
              android_action: JSON.stringify({
                functionName: "NotifyTestPay",
                functionParams: "noOpen"
              }),
              needlogin: "false",
              logTitle: ""
            })
            dsBridge.call("generalAction", { type: "0", ios_action: "ulePopView", android_action: "ulePopView" })
          }
        })
      } catch (err) {
        console.log(err)
      }
    })
  },
  setPassword: () => {
    updatePayWord(
      {
        oldPaymentPwd: encrypted(tabTwo.password), // 旧支付密码
        newPaymentPwd: encrypted(tabThree.password), // 新支付密码
        confirmPwd: encrypted(tabFour.password) // 确认密码
      },
      "",
      "jsonCallback"
    ).then((res) => {
      console.log("=======res", res)
      if (res.code == "0000") {
        //新密码设置完成直接开通生物支付
        data.toSetPayPages()
      } else {
        showToast(res.msg)
      }
    })
  }
})
watch(
  () => [tabOne.password, tabThree.password, tabFour.password],
  (newVal) => {
    if (data.activeName == "tab0") {
      if (newVal[0].length === 6) {
        console.log("==输入完成1", newVal)
        //验证码输入完成进入旧密码输入
        data.activeName = "tab1" //切换到旧密码验证
        setAppTitle("支付密码验证")
      }
    }
    if (data.activeName == "tab2") {
      if (newVal[1].length === 6) {
        console.log("==输入完成2", newVal)

        //新密码输入完成进入确认密码
        data.activeName = "tab3"
        setAppTitle("设置新支付密码")
      }
    }
    if (data.activeName == "tab3") {
      if (newVal[2].length === 6) {
        console.log("==输入完成3", newVal)
        //新密码设置
        tabFour.setPassword()
      }
    }
  }
)

const data = reactive({
  activeName: "tab1",

  // pageStatus: "s", //设置密码s,修改密码m，重置密码r
  // validateCode: "", //验证码
  // oldPassword: "", //旧密码
  // newPassword: "", //新密码
  // password: "", //确认密码
  // phoneNumber: "",
  // titleObj: {
  //   s: "设置支付密码",
  //   m: "更新支付密码",
  //   r: "找回支付密码"
  // },
  changeTabs: (e) => {
    console.log("tabs改变了", e)
  },
  // onSubmit: (values) => {
  //   console.log("submit", values)
  //   if (data.pageStatus == "s") {
  //     //设置支付密码
  //     setPayWord(
  //       {
  //         smsVerifyCode: encrypted(data.validateCode), // 短信验证码
  //         newPaymentPwd: encrypted(data.newPassword), // 新支付密码
  //         confirmPwd: encrypted(data.password) // 确认密码
  //       },
  //       "",
  //       "jsonCallback"
  //     ).then((res) => {
  //       console.log("=======res", res)
  //       if (res.code == "0000") {
  //         data.toSetPayPages()
  //       } else {
  //         showToast(res.msg)
  //       }
  //     })
  //   } else if (data.pageStatus == "m") {
  //     //修改支付密码
  //     updatePayWord(
  //       {
  //         smsVerifyCode: encrypted(data.validateCode), // 短信验证码
  //         newPaymentPwd: encrypted(data.newPassword), // 新支付密码
  //         oldPaymentPwd: encrypted(data.oldPassword), // 旧支付密码
  //         confirmPwd: encrypted(data.password) // 确认密码
  //       },
  //       "",
  //       "jsonCallback"
  //     ).then((res) => {
  //       console.log("=======res", res)
  //       if (res.code == "0000") {
  //         data.toSetPayPages()
  //       } else {
  //         showToast(res.msg)
  //       }
  //     })
  //   } else if (data.pageStatus == "r") {
  //     //找回支付密码
  //     resetPayPwd(
  //       {
  //         smsVerifyCode: encrypted(data.validateCode), // 短信验证码
  //         newPaymentPwd: encrypted(data.newPassword), // 新支付密码
  //         confirmPwd: encrypted(data.password) // 确认密码
  //       },
  //       "",
  //       "jsonCallback"
  //     ).then((res) => {
  //       console.log("=======res", res)
  //       if (res.code == "0000") {
  //         data.toSetPayPages()
  //       } else {
  //         showToast(res.msg)
  //       }
  //     })
  //   }
  // },
  // rePasswordFun: (val) => {
  //   if (val != data.newPassword) {
  //     return "两次密码不一致"
  //   }
  // },
  // toResetPassword: () => {
  //   data.pageStatus = "r"
  // },
  toSetPayPages: () => {
    //app下判断是否支持生物支付，支持则跳转生物支付设置提示页面，不支持则直接会到收银台页面
    loadScript("//i2.ulecdn.com/ulewap/j/cashierDesk/dsbridge.js", (res) => {
      //判断当前设备生物支付支持状态
      data.getBiometricStatus(function (res) {
        console.log("====当前支持的生物识别", res)
        //不支持app新方法直接返回收银台页面
        if (!res || !(res.isHardwareDetected && res.hasEnrolledFingerprints)) {
          //向收银台页面发送消息，通知收银台用户暂不开通生物支付并关闭当前webview
          dsBridge.call("generalAction", {
            type: "6",
            ios_action: JSON.stringify({
              functionName: "NotifyTestPay",
              functionParams: "noOpen"
            }),
            android_action: JSON.stringify({
              functionName: "NotifyTestPay",
              functionParams: "noOpen"
            }),
            needlogin: "false",
            logTitle: ""
          })
          showToast(`${data.titleObj[data.pageStatus]}成功`)
          setTimeout(() => {
            dsBridge.call("generalAction", { type: "0", ios_action: "ulePopView", android_action: "ulePopView" })
          }, 2000)
          return false
        } else {
          tabFour.openPay()
        }
      })
    })
  },
  getBiometricStatus: (callback) => {
    var hasMethod = dsBridge.hasNativeMethod("getBiometricStatus") //是否有当前方法
    if (!hasMethod) {
      return callback()
    }
    dsBridge.call("getBiometricStatus", function (ret) {
      console.log("getBiometricStatus", ret)
      callback && callback(JSON.parse(ret))
    })
  },
  getPageType: function () {
    let userAgent = navigator.userAgent.toLowerCase(),
      pageType = "H5"
    if (userAgent.match(/MicroMessenger/i) == "micromessenger") {
      //微信环境
      if (/miniprogram/.test(ua)) {
        pageType = "微信小程序"
      } else {
        pageType = "微信H5"
      }
    } else {
      if (userAgent.match(/android|adr/i)) {
        pageType = "Android"
      } else if (userAgent.match(/(iphone|ipod|ipad);?/i)) {
        pageType = "iOS"
      } else {
        //浏览器环境
        pageType = "H5"
      }
    }
    return pageType
  },
  getMobileNum: () => {
    getMobileNum({}, "", "jsonCallback").then((res) => {
      if (res.code == "0000") {
        data.phoneNumber = res.data
        if (data.phoneNumber) {
          //神策埋点-忘记密码-曝光
          window.uleStatUtil &&
            window.uleStatUtil.sendSensorTrack("btnExposure", {
              ule_title: window.document.title,
              button_name: "旧密码-忘记密码",
              platform_type: data.getPageType(),
              key_business_name: ""
            })
        }
      } else {
        showToast(res.msg)
      }
    })
  }
})
//验证码发送功能
// const sendSms = reactive({
//   smsStatus: 0, //0未发送，1已发送
//   smsSecond: 60, //倒计时
//   hasSend: false, //是否发送过验证码
//   sendSmsHandler: () => {
//     console.log("sendSms.smsStatus", sendSms.smsStatus)
//     if (data.pageStatus == "r") {
//       //找回密码发送短信验证码
//       sendCodeReset({}, "", "jsonCallback").then((res) => {
//         console.log("=======res", res)
//         if (res.code == "0000") {
//           sendSms.smsStatus = 1
//           sendSms.hasSend = true
//           //请求发送短信接口，调用成功进行倒计时
//           sendSms.timeOutFun()
//         } else {
//           showToast(res.msg || "验证码发送失败，请稍后重试")
//         }
//       })
//     } else {
//       getSmsCode({}, "", "jsonCallback").then((res) => {
//         console.log("=======res", res)
//         if (res.code == "0000") {
//           sendSms.smsStatus = 1
//           sendSms.hasSend = true
//           //请求发送短信接口，调用成功进行倒计时
//           sendSms.timeOutFun()
//         } else {
//           showToast(res.msg || "验证码发送失败，请稍后重试")
//         }
//       })
//     }
//   },
//   timeOutFun: (callback) => {
//     if (sendSms.smsSecond > 0) {
//       setTimeout(() => {
//         sendSms.smsSecond--
//         sendSms.timeOutFun()
//       }, 1000)
//     } else {
//       sendSms.smsStatus = 0
//       sendSms.smsSecond = 60
//     }
//   }
// })
onMounted(() => {
  console.log("地址参数1", route.query)
  data.pageStatus = route.query.status
  data.phoneNumber = route.query.mobile
  // document.title = data.titleObj[data.pageStatus] || "设置支付密码"
  setAppTitle("支付密码验证")
  if (!data.phoneNumber) {
    data.getMobileNum()
  } else {
    //神策埋点-忘记密码-曝光
    window.uleStatUtil &&
      window.uleStatUtil.sendSensorTrack("btnExposure", {
        ule_title: window.document.title,
        button_name: "旧密码-忘记密码",
        platform_type: data.getPageType(),
        key_business_name: ""
      })
  }
})
</script>
<style lang="scss" scoped>
.container {
  :deep(.van-tabs__wrap) {
    display: none;
  }
  .sms_con {
    .title {
      font-size: 38px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #333333;
      line-height: 53px;
      text-align: center;
      margin-top: 66px;
    }
    .tips {
      font-size: 28px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #666666;
      line-height: 40px;
      text-align: center;
    }
  }
  .tops_17 {
    margin-top: 17px;
  }
  .tops_35 {
    margin-top: 35px;
  }
  .tipsActive {
    color: #ff8819;
  }
  .tops_50 {
    margin-top: 50px;
  }
  .tops_82 {
    margin-top: 82px;
  }
  .tops_41 {
    margin-top: 41px;
  }
  .password_con {
    .title {
      font-size: 28px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #666666;
      line-height: 40px;
      text-align: center;
    }

    :deep(.van-field) {
      width: 670px;
      height: 100px;
      // background: #000;
      margin: 41px auto 0;
      border: 1px solid #d2d2d2;
    }
    :deep(.van-field__control::-webkit-input-placeholder) {
      font-size: 28px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #999999;
      text-align: center;
    }
    .submit_btn {
      width: 690px;
      height: 90px;
      background: #ee1919;
      border-radius: 55px;
      font-size: 28px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #ffffff;
      line-height: 90px;
      text-align: center;
      margin: 89px auto 0;
    }
    .submit_btn:active {
      opacity: 0.8;
    }
    .disabled {
      opacity: 0.5;
    }
    .disabled:active {
      opacity: 0.5;
    }
    .forget_pwd {
      display: flex;
      margin-top: 20px;
      flex-direction: row-reverse;
      padding: 0 30px;
      span {
        font-size: 28px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #ee1919;
        line-height: 40px;
      }
    }
  }
  :deep(.van-password-input__cursor) {
    background: linear-gradient(360deg, #fd8e22 0%, #fc5245 100%);
  }
  :deep(.van-password-input__item--focus) {
    border: 1px solid #fda358;
  }
}
</style>
